// pages/ai/ai.js
var app = getApp();
Page({
  data: {
    navbar: [ '活动中心', '卧室'],
    currentTab: 0,
    age:"",
    src3:'http://tmp/5WAc2Wq4YPVx4327d42f83bf255401e53dba82efd9f3.jpg',
    src2:"",
    emotion1:"",
    sum:0,
    src:"",
    src1:"",
    who:"",
    openid: "",
    token: "",
    userInfo:[],
    windowWidth: 0,
    access_token:'',
    access_token1:'',
    methoddata:{},
  adress:""
  },
  navbarTap: function(e){
    this.setData({
      currentTab: e.currentTarget.dataset.idx
    })
    if(this.data.currentTab===0){
      this.takePhoto()
      this.interval1=setInterval(this.takePhoto,2000)
    }else{
      clearInterval(this.interval1)
    }
    if(this.data.currentTab===1){
      this.takePhoto1()
      this.interval=setInterval(this.takePhoto1,2000)
    }else{
      clearInterval(this.interval)
    }
  },
  onLoad() {
    var that = this
    //屏幕宽度
    var sysInfo = wx.getSystemInfoSync();
    that.setData({
      windowWidth: sysInfo.windowWidth,
    })
    that.ctx = wx.createCameraContext()
      that.setData({
        userInfo:app.globalData.userInfo,
        oldman:app.globalData.oldman,
      });
    
    // 每次更新access_token
    //活动中心
    wx.request({
      url: "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=FNwQMBIRA8OsEb4vzvZghMQt&client_secret=XAHrTL78prjqz8KPY7SYKPhoDSFPT6Ur",
      dataType: "json",
      header: {
         'content-type': 'application/json; charset=UTF-8'
      },
      method: 'POST',
      success: function (res) {
        app.globalData.access_token = res.data.access_token;
        // 判断上个页面是否传递值下来
        that.setData({
      access_token: res.data.access_token,
      })
      },
    }) 
    //卧室
    wx.request({
      url: "https://open.ys7.com/api/lapp/token/get?appKey=419538bd56db4853bb3dbc992d97a10c&appSecret=6e030e8572d39953c565d0997d2629ad",
      method: 'POST',
      dataType: "json",
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        //  console.log(res.data.data.accessToken);
        that.setData({
          access_token1: res.data.data.accessToken
        });
      }
    })
	this.setData({
		 adress:app.globalData.data.markers[app.globalData.id].callout.content,
    });
  },
  onReady: function () {
  },
   back:function(){
      wx.navigateBack({
        delta: 1,
      })
    },
//活动中心
  takePhoto() {
    // console.log("开始拍照takePhoto")
    var that = this
    var takephonewidth
    var takephoneheight
    that.ctx.takePhoto({
      quality: 'low',
      success: (res) => {
        that.setData({
          src: res.tempImagePath
        })
        // 获取图片真实宽高
        wx.getImageInfo({
          src: res.tempImagePath,
          success: function (res) {
            takephonewidth= res.width,
            takephoneheight = res.height
          }
        })
        // console.log(takephonewidth, takephoneheight)
        wx.getFileSystemManager().readFile({
          filePath: res.tempImagePath, //选择图片返回的相对路径
          encoding: 'base64', //编码格式
          success: res => { //成功的回调
            // console.log(that.data)
            // console.log(res)
            //活动中心
            wx.request({
              url: "https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=" + that.data.access_token,
              data: {
                image:res.data,
                image_type:"BASE64",
                max_face_num:10,
                face_field:'age,beauty,emotion'
              },
              // dataType: "json",
              header: {
                'content-type': 'application/json; charset=UTF-8'
               },
               method: 'POST',
              success: function (res) {
                // console.log(res)
                if (res.data.error_code === 0) { 
                  var ctx = wx.createContext()
                  ctx.setStrokeStyle('yellow')//方框
                  // ctx.lineWidth = 3
                  ctx.setLineWidth(3)
                  for (let j = 0; j < res.data.result.face_num; j++){
                    var cavansl = res.data.result.face_list[j].location.left / takephonewidth * that.data.windowWidth
                    var cavanst = res.data.result.face_list[j].location.top / takephoneheight * that.data.windowWidth
                    var cavansw = res.data.result.face_list[j].location.width / takephonewidth * that.data.windowWidth
                    var cavansh = res.data.result.face_list[j].location.height / takephoneheight * that.data.windowWidth
                    var emotionType = res.data.result.face_list[j].emotion.type;
                    var emotion = '';
                    // console.log(takephonewidth * that.data.windowWidth)
                    if (emotionType =='angry'){
                      emotion = '愤怒';
                    }else if (emotionType == 'disgust') {
                      emotion = '厌恶';
                    }else if (emotionType == 'fear') {
                      emotion = '恐惧';
                    }else if (emotionType == 'happy') {
                      emotion = '高兴';
                    }else if (emotionType == 'sad') {
                      emotion = '伤心';
                    }else if (emotionType == 'surprise') {
                      emotion = '惊讶';
                    } else if (emotionType == 'neutral'){
                      emotion = '无情绪';
                    }else{
                      emotion = '未知表情';
                    }
                    var cavanstext = '年龄:' + res.data.result.face_list[j].age + ' 颜值:' + res.data.result.face_list[j].beauty + ' 表情:' + emotion
                    that.setData({
                      age:res.data.result.face_list[0].age,
                      emotion1:emotion,
                    })
                    ctx.setFontSize(14);
                    ctx.setFillStyle("blue")//文本颜色
                    ctx.fillText(cavanstext, cavansl, cavanst - 2)
                     ctx.strokeRect(cavansl, cavanst, cavansw, cavansh)
                  }
                     wx.drawCanvas({
                                      canvasId: 'canvas',
                                      actions: ctx.getActions()
                                    })
                                  } else{
                                  var ctx = wx.createContext()
                                  ctx.setStrokeStyle('black')
                                  ctx.lineWidth = 3
                                  wx.drawCanvas({
                                    canvasId: 'canvas',
                                    actions: ctx.getActions()
                                  })               
                }
                // console.log(res.data.result.face_list[0].emotion.type)
                if(that.data.emotion1==='高兴'){
                  that.data.sum++
                  if(that.data.sum>3){
                    wx.request({
                      url:'http://localhost:8080/api_v1/sendSMS2', //接口地址
                     
                      menthod: 'GET',
                      header:{
                        'content-type':'application/json'   //默认值
                      },
                      success:function(res) {
                        console.log(res.data)
                      },
                      fail:function(res) {
                        console.log("......fail......")
                        console.log(res.data)
                        console.log("......fail......")
                      }
                    });
                    wx.showToast({
                      title: '提交成功',
                      icon: 'succes',
                      duration: 1500,
                      mask: true,
                      success: function () {
                        setTimeout(function () {
                          wx.reLaunch({
                            url: '../index/index'
                          })
                        }, 1500)
                      }
                    }); 
                  }
                }
              },
              })
              }
          })
        }
      }
    )
  },
  //卧室
  takePhoto1() {
    var that = this
    var takephonewidth
    var takephoneheight
    wx.request({
      url: 'https://open.ys7.com/api/lapp/device/capture?accessToken='+ that.data.access_token1,
      data:{
        deviceSerial:"F30656963",
        channelNo:1,
      },
      header: {
            'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'
            },
       method:'POST',
      success:function(res){
        // console.log(res)
        // that.setData({
        //         src1: res.data.data.picUrl
        // })
            wx.getImageInfo({
          // src:'https://fastgw-ali.ys7.com/1/capture/2021/5/19/2m1blkcjro96t1a4viq7oa8zk.jpg?Expires=1621480183&OSSAccessKeyId=LTAIzI38nEHqg64n&Signature=xzpEcrzOCGmydIxL2dMTB4uRNkM%3D&bucket=ezviz-fastdfs-gateway',
          src:that.data.src1,
          success: function (e) {
            takephonewidth= e.width,
            takephoneheight = e.height
            // console.log(e.path)
            that.setData({
              src2: e.path
            })
          },fail(){
            console.log("2222")
          }
        })
        wx.getFileSystemManager().readFile({
          // filePath: "http://tmp/5WAc2Wq4YPVx4327d42f83bf255401e53dba82efd9f3.jpg",
          filePath: that.data.src2, //选择图片返回的相对路径
          encoding: 'base64', //编码格式
          success: res => { //成功的回调
            console.log(res)
            wx.request({
              url: "https://open.ys7.com/api/lapp/intelligence/face/analysis/detect?accessToken=" + that.data.access_token1,
              data: {
                image:res.data,
                dataType:1,
                operation:'age,expression,faceScore'
              },
              header: {
                'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'
               },
               method: 'post',
              success: function (res) {
                // console.log(res.data.code);
                if (res.data.code = 200) { 
                  var ctx = wx.createContext()
                  ctx.setStrokeStyle('yellow')
                  // ctx.lineWidth = 3
                  ctx.setLineWidth(3)
                  for (let j = 0; j < res.data.data.faces.length; j++){
                    var cavansl = res.data.data.faces[j].location.x / takephonewidth * that.data.windowWidth
                    var cavanst = res.data.data.faces[j].location.y / takephoneheight * that.data.windowWidth
                    var cavansw = res.data.data.faces[j].location.width / takephonewidth * that.data.windowWidth
                    var cavansh = res.data.data.faces[j].location.height / takephoneheight * that.data.windowWidth
                    var emotionType = res.data.data.faces[j].smile.value;
                    var emotion = '';
                    // console.log(takephonewidth * that.data.windowWidth)
                    // console.log(res.data.data.faces[j].location.x)
                    // console.log(res.data.data.faces[j].smile.value)
                    if (emotionType ==1){
                      emotion = '中性';
                    }else if (emotionType == 2) {
                      emotion = '高兴';
                    }else if (emotionType == 3) {
                      emotion = '惊讶';
                    }else if (emotionType == 4) {
                      emotion = '害怕';
                    }else if (emotionType == 5) {
                      emotion = '厌恶';
                    }else if (emotionType == 6) {
                      emotion = '难过';
                    } else if (emotionType ==7){
                      emotion = '愤怒';
                    }else{
                      emotion = '未知表情';
                    }
                  var cavanstext = '年龄:' + res.data.data.faces[j].age.value + ' 颜值:' + res.data.data.faces[j].faceIQA.totalQuality + ' 表情:' + emotion
                      ctx.setFontSize(14);
                    ctx.setFillStyle("blue")//文本颜色
                    ctx.fillText(cavanstext, cavansl, cavanst - 2)
                     ctx.strokeRect(cavansl, cavanst, cavansw, cavansh)
                }
                wx.drawCanvas({
                       canvasId: 'canvas1',
                                      actions: ctx.getActions()
                                    })
                                  } else{
                                  var ctx = wx.createContext()
                                  ctx.setStrokeStyle('black')
                                  ctx.lineWidth = 3
                                  wx.drawCanvas({
                                    canvasId: 'canvas1',
                                    actions: ctx.getActions()
                                  })               
                }
                // // console.log(res.data.result.face_list[0].emotion.type)
                if(that.data.emotion1==='高兴'){
                  that.data.sum++
                  if(that.data.sum>3){
                    console.log("sanci")
                    wx.request({
                      url:'http://localhost:8080/api_v1/sendSMS2', //接口地址
                     
                      menthod: 'GET',
                      header:{
                        'content-type':'application/json'   //默认值
                      },
                      success:function(res) {
                        console.log(res.data)
                      },
                      fail:function(res) {
                        console.log("......fail......")
                        console.log(res.data)
                        console.log("......fail......")
                      }
                    });
                    wx.showToast({
                      title: '提交成功',
                      icon: 'succes',
                      duration: 1500,
                      mask: true,
                      success: function () {
                        setTimeout(function () {
                          wx.reLaunch({
                            url: '../index/index'
                          })
                        }, 1500)
                      }
                    });
                  }
                }

              },
              })
              },fail(){
                console.log("hhh")
              },
          })
      },
    })
  },
//活动中心
 search(){
    var that = this
    var takephonewidth
    var takephoneheight
    that.ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        console.log(res.tempImagePath),
        // 获取图片真实宽高
        wx.getImageInfo({
          src: res.tempImagePath,
          success: function (res) {
            takephonewidth = res.width,
              takephoneheight = res.height
          }
        })
        that.setData({
          src: res.tempImagePath
        }),
        wx.getFileSystemManager().readFile({
          filePath: that.data.src, //选择图片返回的相对路径
          encoding: 'base64', //编码格式
          success: res => {
            // console.log(res)
            wx.request({
              url: "https://aip.baidubce.com/rest/2.0/face/v3/search?access_token=" + that.data.access_token,
              data: {
                image: res.data,
                image_type: "BASE64",
                group_id_list: "AAS",
                max_face_num: 10,
                match_threshold: 60,

              },
              method: 'POST',
              dataType: "json",
              header: {
                'content-type': 'application/json'
              },
              success: function (res) {
                that.setData({
                  who:res.data.result.user_list[0].user_id
                })
                  var ctx = wx.createContext()
                  if (res.data.error_code === 0) {
                    ctx.setStrokeStyle('#31859c')
                    ctx.setFillStyle('#31859c');
                    ctx.lineWidth = 3
                    for (let j = 0; j < res.data.result.face_num; j++) {
                      var cavansl = res.data.result.face_list[j].location.left / takephonewidth * that.data.windowWidth/2
                      var cavanst = res.data.result.face_list[j].location.top / takephoneheight * that.data.windowWidth/2
                      var cavansw = res.data.result.face_list[j].location.width / takephonewidth * that.data.windowWidth/2
                      var cavansh = res.data.result.face_list[j].location.height / takephoneheight * that.data.windowWidth/2
                      var cavanstext = res.data.result.face_list[j].user_list.length>0?res.data.result.face_list[j].user_list[0].user_id + " " + res.data.result.face_list[j].user_list[0].score.toFixed(0) + "%":"Unknow"
                      ctx.setFontSize(14);
                      ctx.fillText(cavanstext, cavansl, cavanst-2)
                      ctx.strokeRect(cavansl, cavanst, cavansw, cavansh)
                    }
                    wx.drawCanvas({
                      canvasId: 'canvasresult',
                      actions: ctx.getActions()
                    })
                  } else {
                    that.setData({
                      who: res.data.error_msg
                    })
                    var ctx = wx.createContext()
                    ctx.setStrokeStyle('#31859c')
                    ctx.lineWidth = 3
                    wx.drawCanvas({
                      canvasId: 'canvasresult',
                      actions: ctx.getActions()
                    })
                  }
              },
            })
          }
        })
      }
    })

  },
// search1(){
//   wx.getFileSystemManager().readFile({
//     filePath: that.data.src2, //选择图片返回的相对路径
//     encoding: 'base64', //编码格式
//     success: res => {
//       // console.log(res)
//       wx.request({
//         url: "https://open.ys7.com/api/lapp/intelligence/face/analysis/search?access_token1=" + that.data.access_token1,
//         data: {
//           image: res.data,
//           image_type: "BASE64",
//           group_id_list: "AAS",
//           max_face_num: 10,
//           match_threshold: 60,

//         },
//         method: 'POST',
//         dataType: "json",
//         header: {
//           'content-type': 'application/json'
//         },
//         success: function (res) {
//           console.log(res)
//           // that.setData({
//           //   who:res.data.result.user_list[0].user_id
//           // })
//           //   var ctx = wx.createContext()
//           //   if (res.data.error_code === 0) {
//           //     ctx.setStrokeStyle('#31859c')
//           //     ctx.setFillStyle('#31859c');
//           //     ctx.lineWidth = 3
//           //     for (let j = 0; j < res.data.result.face_num; j++) {
//           //       var cavansl = res.data.result.face_list[j].location.left / takephonewidth * that.data.windowWidth/2
//           //       var cavanst = res.data.result.face_list[j].location.top / takephoneheight * that.data.windowWidth/2
//           //       var cavansw = res.data.result.face_list[j].location.width / takephonewidth * that.data.windowWidth/2
//           //       var cavansh = res.data.result.face_list[j].location.height / takephoneheight * that.data.windowWidth/2
//           //       var cavanstext = res.data.result.face_list[j].user_list.length>0?res.data.result.face_list[j].user_list[0].user_id + " " + res.data.result.face_list[j].user_list[0].score.toFixed(0) + "%":"Unknow"
//           //       ctx.setFontSize(14);
//           //       ctx.fillText(cavanstext, cavansl, cavanst-2)
//           //       ctx.strokeRect(cavansl, cavanst, cavansw, cavansh)
//           //     }
//           //     wx.drawCanvas({
//           //       canvasId: 'canvasresult',
//           //       actions: ctx.getActions()
//           //     })
//           //   } else {
//           //     that.setData({
//           //       who: res.data.error_msg
//           //     })
//           //     var ctx = wx.createContext()
//           //     ctx.setStrokeStyle('#31859c')
//           //     ctx.lineWidth = 3
//           //     wx.drawCanvas({
//           //       canvasId: 'canvasresult',
//           //       actions: ctx.getActions()
//           //     })
//           //   }
//         },
//       })
//     }
//   })

// },

  handleBtn() {
    console.log(navbar.methoddata)
    wx.request({
      url:'http://localhost:8080/api_v1/register', //接口地址
      data: {
        "methoddata":navbar.methoddata
      },
      menthod: 'GET',
      header:{
        'content-type':'application/json'   //默认值
      },
      success:function(res) {
        console.log(res.data)

      },
      fail:function(res) {
        console.log("......fail......")
        console.log(res.data)
        console.log("......fail......")
      }
    });
    wx.showToast({
      title: '提交成功',
      icon: 'succes',
      duration: 1500,
      mask: true,
      success: function () {
        setTimeout(function () {
          wx.reLaunch({
            url: '../index/index'
          })
        }, 1500)
      }
    });
  }
})